#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-rsyncd
# REQUIRE: FILESYSTEMS
# BEFORE: rsyncd

. /etc/rc.subr

#
# TODO: this is really just a place holder for the moment....
#
generate_rsyncd()
{
    RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
    trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT
    local IFS="|"
    local f="rsyncd_port"
    eval local $f
    local cmd cfg
    local sf=$(var_to_sf $f)
    cfg=/usr/local/etc/rsyncd.conf
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT $sf FROM services_rsyncd ORDER BY -id LIMIT 1" | \
	while eval read -r $f; do
	    cat > $cfg <<EOF
use chroot = yes
max connections = 4
pid file = /var/run/rsyncd.pid
EOF
	    if [ "$rsyncd_port" -ne 873 ]; then
		echo "port  = $rsyncd_port" >> $cfg
	    fi
    done
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT rsyncd_auxiliary FROM services_rsyncd ORDER BY -id LIMIT 1" >> $cfg

    local f="id rsyncmod_name rsyncmod_comment rsyncmod_path rsyncmod_mode rsyncmod_maxconn rsyncmod_user rsyncmod_group rsyncmod_hostsallow rsyncmod_hostsdeny"
    eval local $f
    local sf=$(var_to_sf $f)
    local cmd cfg
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT $sf FROM services_rsyncmod ORDER BY id" | \
	while eval read -r $f; do
	    cat >> $cfg <<EOF
[${rsyncmod_name}]
    path = ${rsyncmod_path}
    max connections = ${rsyncmod_maxconn}
    uid = ${rsyncmod_user}
    gid = ${rsyncmod_group}
EOF
		if [ -n "${rsyncmod_comment}" ]; then
			echo "    comment = ${rsyncmod_comment}" >> $cfg
		fi
	    if [ "${rsyncmod_mode}" = "ro" ]; then
		    echo "    write only = false" >> $cfg
		    echo "    read only = true" >> $cfg
	    elif [ "${rsyncmod_mode}" = "wo" ]; then
		    echo "    write only = true" >> $cfg
		    echo "    read only = false" >> $cfg
	    elif [ "${rsyncmod_mode}" = "rw" ]; then
		    echo "    read only = false" >> $cfg
		    echo "    write only = false" >> $cfg
	    fi

	    if [ -n "${rsyncmod_hostsallow}" ]; then
            echo "    hosts allow = ${rsyncmod_hostsallow}" >> $cfg
        fi

	    if [ -n "${rsyncmod_hostsdeny}" ]; then
            echo "    hosts deny = ${rsyncmod_hostsdeny}" >> $cfg
        fi
        ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	    "SELECT rsyncmod_auxiliary FROM services_rsyncmod WHERE id = ${id}" >> $cfg
    done
}

name="ix-rsyncd"
start_cmd='generate_rsyncd'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
